from PIL import Image, ImageDraw
import matplotlib.pyplot as plt

# 打开图像文件
image = Image.open('figure.png')

# 将图像转换为灰度模式
gray_image = image.convert('L')

# 计算灰度直方图
histogram = gray_image.histogram()

# 创建一个新的图像，用于绘制直方图
hist_image = Image.new('RGB', (256, 200), color='white')
draw = ImageDraw.Draw(hist_image)

# 绘制直方图
max_count = max(histogram)
for i in range(256):
    value = histogram[i] / max_count * 200
    draw.line((i, 200, i, 200 - value), fill='black')

# 显示原始图像和直方图
plt.figure(figsize=(10, 5))
plt.subplot(121)
plt.imshow(gray_image, cmap='gray')
plt.title('原始灰度图像')
plt.axis('off')

plt.subplot(122)
plt.imshow(hist_image)
plt.title('灰度直方图')
plt.axis('off')

plt.show()
